import json
import math
from urllib.parse import urlencode

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class NeimengguTlskeqzyhqrmzf083aPolicy(BaseTaxPolicySpider):
    name = "neimenggu_tlskeqzyhqrmzf_083a_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "通辽市"  # 取表格
    county: str = "科尔沁左翼后旗"  # 取表格
    park: str = ""  # 取表格
    source: str = "通辽市科尔沁左翼后旗人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.houqi.gov.cn/zwgk/zfxxgk/zc_1/xzgfxwj_1/xxyxgfxwjk_1/"  # 注明入口网址，以便后续排错
    host = url.split('.gov.cn')[0] + '.gov.cn'
    data_url = host + '/nmsearch/openSearch/gfxwjkList'
    custom_settings = {"DOWNLOAD_TIMEOUT": 60}
    headers = {
        # "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }

    def start_requests(self):
        urls = [self.url]
        for url in urls:
            yield scrapy.Request(url, callback=self.parse_response)

    def parse_response(self, response, **kwargs):
        siteid = response.xpath("//script").re(r"""siteid=(.*?)&""")[0]
        chnid = response.xpath("//script").re(r"""chnid=(.*?)&""")[0]
        data = {
            "validity": "有效",
            "sort": "time",
            "publisher": "",
            "siteid": siteid,
            "chnid": chnid,
            "pageNum": "1",
            "pageSize": "10"
        }
        query_string = urlencode(data)
        url = f"{self.data_url}?{query_string}"
        yield self.Request(
            url,
            headers=self.headers,
            callback=self.parse_list,
            meta={'data': data}
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        # print(response.url)
        for elem in response.json()['data']['data']:
            item = Item()
            item['source_url'] = elem['docpuburl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['docpubtime']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta.get('data')
            total = response.json()['data']['total']
            print("total", response.json()['data']['total'])
            for page_num in range(2, math.ceil(total / 10) + 1):
                data['pageNum'] = page_num
                query_string = urlencode(data)
                url = f"{self.data_url}?{query_string}"
                yield response.follow(url, headers=self.headers,
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_tlskeqzyhqrmzf_083a_policy".split())
